<template>
  <div class="takeoff-landing-container">
    <!-- 左侧查询面板 -->
    <div class="query-panel">
      <h3>起降能力分析</h3>
          <el-form :model="queryForm" label-position="top">
        <el-form-item label="跑道模式">
          <el-radio-group v-model="queryForm.runwayMode">
            <el-radio-button value="before">加宽前</el-radio-button>
            <el-radio-button value="after">加宽后</el-radio-button>
          </el-radio-group>
        </el-form-item>
            <el-form-item label="任务类型">
          <el-select
            v-model="queryForm.missionType"
            placeholder="请选择任务类型"
            @change="handleMissionTypeChange"
          >
            <el-option
              v-for="type in missionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
              </el-select>
            </el-form-item>
        <el-form-item label="飞机型号">
          <el-select
            v-model="queryForm.aircraftType"
            placeholder="请选择飞机型号"
            :disabled="!queryForm.missionType"
          >
            <el-option
              v-for="aircraft in aircraftList"
              :key="aircraft.id"
              :label="aircraft.name"
              :value="aircraft.id"
            />
              </el-select>
            </el-form-item>
            <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleQuery"
          >
            查询
          </el-button>
            </el-form-item>
          </el-form>

      <!-- 查询结果列表 -->
      <div v-if="analysisData.length > 0" class="query-results">
        <h4>查询结果</h4>
        <el-scrollbar height="300px">
          <div 
            v-for="airport in matchedAirports" 
            :key="airport.id" 
            class="airport-item"
            :class="{ active: selectedAirport && selectedAirport.id === airport.id }"
            @click="selectAirport(airport)"
          >
            <div class="airport-name">{{ airport.name }}</div>
            <div class="airport-value">总窗格值: {{ airport.total_window_value }}</div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 中间数据展示区域 -->
    <div class="content-area">
      <!-- 散点图区域 -->
      <div class="scatter-chart-container">
        <h4>机场跑道容量散点图 ({{ queryForm.runwayMode === 'before' ? '加宽前' : '加宽后' }})</h4>
        <div id="scatterChart"></div>
      </div>

      <!-- 地图区域 -->
      <div class="map-container">
        <div id="map"></div>
        <div v-if="loading" class="loading-overlay">
          <div class="spinner"></div>
        </div>
      </div>
            </div>

    <!-- 右侧图表区域 -->
    <div class="chart-panel" v-if="false">
      <h3>窗格值统计</h3>
      <div id="barChart" ></div>
            </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, computed, defineComponent, nextTick } from 'vue'
import * as echarts from 'echarts'
import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { ElMessage } from 'element-plus'
import { getAircraft, getRoles } from '@/api/aircraft'
import { getRunwayAnalysis } from '@/api/runways'
import { getAirports } from '@/api/airports'

// 修复 Leaflet 图标路径问题
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: '/assets/marker-icon-2x.png',
  iconUrl: '/assets/marker-icon.png',
  shadowUrl: '/assets/marker-shadow.png'
})

export default defineComponent({
  name: 'TakeoffLanding',
  setup() {
    // 查询表单数据
    const queryForm = ref({
      runwayMode: 'before',
      missionType: '',
      aircraftType: null
    })

    // 状态数据
    const loading = ref(false)
    const mapInstance = ref(null)
    const markersLayer = ref(null)
    const markers = ref([])
    const barChart = ref(null)
    const scatterChart = ref(null)
    const selectedAirport = ref(null)
    const aircraftList = ref([])
    const analysisData = ref([])
    const missionTypes = ref([])

    // 计算属性
    const matchedAirports = computed(() => {
      if (!queryForm.value.aircraftType) return analysisData.value
      return analysisData.value.filter(airport => airport.total_window_value > 0)
    })

    // 初始化地图
    const initMap = () => {
      if (mapInstance.value) {
        mapInstance.value.remove()
      }

      const center = [23.7, 121.0]
      const bounds = [
        [21.5, 119.0], // 西南角
        [25.5, 123.0]  // 东北角
      ]

      const map = L.map('map', {
        center,
        zoom: 9,
        maxBounds: bounds,
        minZoom: 8,
        maxZoom: 13,
        zoomControl: true,
        scaleControl: true
      })

      mapInstance.value = map

      // 添加离线地图图层
      const offlineLayer = L.tileLayer('/assets/map-of-taiwan/gaode_map/{z}/{x}/{y}.png', {
        minZoom: 8,
        maxZoom: 11,
        tileSize: 256,
        attribution: '高德地图离线数据',
        errorTileUrl: '',
        noWrap: true,
        bounds: L.latLngBounds(
          L.latLng(20.63278, 119.53125),  // 西南角
          L.latLng(25.79989, 122.34375)   // 东北角
        ),
        tms: false,
        crossOrigin: true,
        subdomains: '',
        detectRetina: false
      })

      offlineLayer.on('tileerror', function(e) {
        console.error('Tile error:', e.tile.src)
        e.tile.style.backgroundColor = '#f0f0f0'
      })

      offlineLayer.addTo(map)
      markersLayer.value = L.layerGroup().addTo(map)
    }

    // 初始化散点图
    const initScatterChart = () => {
      if (!scatterChart.value) {
        const element = document.getElementById('scatterChart')
        if (element) {
          scatterChart.value = echarts.init(element)
        }
      }
      
      if (!scatterChart.value) return
      
      const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
            return `${params.data.name}<br/>跑道数量: ${params.data.runways.length}<br/>总窗格值: ${params.data.value}`
      }
    },
    xAxis: {
      type: 'value',
          name: '跑道数量',
          nameLocation: 'middle',
          nameGap: 30,
          min: 0,
          max: function(value) {
            return Math.ceil(value.max) + 1
          }
    },
    yAxis: {
      type: 'value',
          name: '总窗格值',
          nameLocation: 'middle',
          nameGap: 30,
          min: 0
    },
    series: [{
      type: 'scatter',
          symbolSize: function(data) {
            return Math.sqrt(data[2]) * 5
          },
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(64, 158, 255, 0.5)'
            }
          }
        }]
      }
      
      scatterChart.value.setOption(option)
    }

    // 更新散点图
    const updateScatterChart = () => {
      if (!scatterChart.value) {
        initScatterChart()
      }
      
      if (!scatterChart.value) return
      
      const scatterData = matchedAirports.value.map(airport => {
        return {
          name: airport.name,
          value: [
            airport.runways.length,
            airport.total_window_value,
            airport.total_window_value
          ],
          runways: airport.runways,
      itemStyle: {
            color: selectedAirport.value && selectedAirport.value.id === airport.id 
              ? '#ff7730' 
              : '#409EFF'
          }
        }
      })
      
      const option = {
        series: [{
          data: scatterData
        }]
      }
      
      try {
        scatterChart.value.setOption(option)
        
        // 注册点击事件
        scatterChart.value.off('click')
        scatterChart.value.on('click', (params) => {
          const airportName = params.data.name
          const airport = matchedAirports.value.find(a => a.name === airportName)
          if (airport) {
            selectAirport(airport)
          }
        })
      } catch (error) {
        console.error('更新散点图失败:', error)
      }
    }

    // 更新地图标记
    const updateMapMarkers = () => {
      if (!markersLayer.value || !mapInstance.value) return
      
      // 清除现有标记
      markers.value.forEach(marker => marker.remove())
      markers.value = []
      markersLayer.value.clearLayers()

      // 只在有数据时添加标记
      if (matchedAirports.value && matchedAirports.value.length > 0) {
        matchedAirports.value.forEach(airport => {
          if (airport.latitude && airport.longitude) {
            // 在地图上添加圆形标记
            const position = [airport.latitude, airport.longitude]
            const marker = L.circleMarker(position, {
              radius: Math.min(20, Math.max(5, Math.sqrt(airport.total_window_value || 0))),
              fillColor: selectedAirport.value && selectedAirport.value.id === airport.id 
                ? '#ff7730' 
                : '#409EFF',
              color: '#fff',
              weight: 1,
              opacity: 1,
              fillOpacity: 0.8
            })

            marker.bindPopup(`
              <div class="airport-popup">
                <h3>${airport.name}</h3>
                <p>区域: ${airport.region || '未知'}</p>
                <p>总窗格值: ${airport.total_window_value || 0}</p>
                <p>跑道数量: ${airport.runways ? airport.runways.length : 0}</p>
              </div>
            `)
            
            marker.on('click', () => {
              selectAirport(airport)
            })

            marker.addTo(markersLayer.value)
            markers.value.push(marker)
          }
        })

        // 自动调整地图视图以显示所有标记
        if (markers.value.length > 0 && !selectedAirport.value) {
          const group = L.featureGroup(markers.value)
          mapInstance.value.fitBounds(group.getBounds(), {
            padding: [50, 50],
            maxZoom: 11
          })
        }
      }
    }
  
  // 更新柱状图
    const updateBarChart = () => {
      if (!barChart.value) {
        const element = document.getElementById('barChart')
        if (element) {
          barChart.value = echarts.init(element)
        }
      }

      if (!barChart.value) return
      
      let data = []
      
      if (selectedAirport.value && selectedAirport.value.runways) {
        // 如果选中了机场，显示该机场的各条跑道窗格值
        data = selectedAirport.value.runways.map(runway => ({
          name: runway.name,
          value: runway.window_value
        }))
      } else if (matchedAirports.value && matchedAirports.value.length > 0) {
        // 如果没有选中机场，显示所有机场的总窗格值
        data = matchedAirports.value.map(airport => ({
          name: airport.name,
          value: airport.total_window_value || 0
        })).sort((a, b) => b.value - a.value).slice(0, 10)
      }

      const option = {
    title: {
          text: selectedAirport.value ? `${selectedAirport.value.name} - 跑道窗格值` : '机场总窗格值排名',
          left: 'center',
          textStyle: {
            fontSize: 14
          }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
        grid: {
          left: '3%',
          right: '15%',
          bottom: '3%',
          top: 50,
          containLabel: true
    },
    xAxis: {
          type: 'value',
          name: '窗格值',
      axisLabel: {
            formatter: '{value}'
      }
    },
    yAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLabel: {
            interval: 0,
            rotate: 0
          }
    },
    series: [{
          name: '窗格值',
      type: 'bar',
          data: data.map(item => ({
            value: item.value,
      itemStyle: {
              color: '#409EFF'
            }
          })),
          label: {
            show: true,
            position: 'right',
            formatter: '{c}'
          }
        }]
      }

      try {
        barChart.value.setOption(option, true)
      } catch (error) {
        console.error('更新图表失败:', error)
      }
    }

    // 获取任务类型
    const getMissionTypes = async () => {
      try {
        const response = await getRoles()
        if (response && Array.isArray(response)) {
          missionTypes.value = response
        } else {
          ElMessage.error('获取任务类型失败：数据格式错误')
        }
      } catch (error) {
        console.error('获取任务类型失败:', error)
        ElMessage.error('获取任务类型失败')
      }
    }

    // 任务类型变化处理
    const handleMissionTypeChange = async (value) => {
      queryForm.value.aircraftType = null
      selectedAirport.value = null
      analysisData.value = []
      
      try {
        const response = await getAircraft(value)
        if (response && Array.isArray(response)) {
          aircraftList.value = response
        } else {
          ElMessage.error('获取飞机列表失败：数据格式错误')
          aircraftList.value = []
        }
      } catch (error) {
        console.error('获取飞机列表失败:', error)
        ElMessage.error('获取飞机列表失败')
        aircraftList.value = []
      }
    }

    // 查询处理
    const handleQuery = async () => {
      if (!queryForm.value.aircraftType) {
        ElMessage.warning('请选择飞机型号')
        return
      }

      loading.value = true
      selectedAirport.value = null
      
      try {
        // 使用API获取跑道分析数据
        const params = {
          mode: queryForm.value.runwayMode,
          aircraft_id: queryForm.value.aircraftType
        }
        const response = await getRunwayAnalysis(params)
        
        if (response && Array.isArray(response)) {
          analysisData.value = response
          updateMapMarkers()
          updateScatterChart()
          updateBarChart()
        } else {
          ElMessage.error('获取分析数据失败：数据格式错误')
          analysisData.value = []
        }
      } catch (error) {
        console.error('获取分析数据失败:', error)
        ElMessage.error('获取分析数据失败')
        analysisData.value = []
      } finally {
        loading.value = false
      }
    }

    // 选择机场
    const selectAirport = (airport) => {
      selectedAirport.value = airport
      if (mapInstance.value && airport.latitude && airport.longitude) {
        const position = [airport.latitude, airport.longitude]
        mapInstance.value.setView(position, 9)
      }
      updateMapMarkers() // 更新地图标记，突出显示选中的机场
      updateScatterChart() // 更新散点图，突出显示选中的机场
      updateBarChart() // 更新柱状图，显示选中机场的跑道窗格值
    }

    // 初始化加载机场数据
    const loadInitialData = async () => {
      try {
        loading.value = true
        
        // 使用机场API服务获取数据
        const response = await getAirports()
        
        if (!response || !Array.isArray(response)) {
          throw new Error('获取机场数据失败：数据格式错误')
        }
        
        // 处理数据以适应应用需求
        analysisData.value = response.map(airport => ({
          ...airport,
          total_window_value: 0, // 初始窗格值为0，后续分析时会更新
          runways: airport.runways || []
        }))
        
        updateMapMarkers()
        updateScatterChart()
        updateBarChart()
        
        // 显示消息
        ElMessage.success(`成功加载 ${response.length} 个机场数据`)
      } catch (error) {
        console.error('加载机场数据失败:', error)
        ElMessage.error('加载机场数据失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    // 生命周期钩子
    onMounted(async () => {
      window.addEventListener('resize', handleResize)
      
      // 获取任务类型
      await getMissionTypes()
      
      // 初始化地图和图表
      nextTick(async () => {
        try {
          initMap()
          initScatterChart()
          updateBarChart()
          
          // 加载初始机场数据
          await loadInitialData()
        } catch (error) {
          console.error('初始化失败:', error)
        }
      })
    })
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      
      if (barChart.value) {
        barChart.value.dispose()
        barChart.value = null
      }
      
      if (scatterChart.value) {
        scatterChart.value.dispose()
        scatterChart.value = null
      }
      
      if (mapInstance.value) {
        mapInstance.value.remove()
        mapInstance.value = null
      }
      
      if (markers.value.length) {
        markers.value.forEach(marker => marker.remove())
        markers.value = []
      }
    })

    // 添加窗口大小变化处理
    const handleResize = () => {
      if (barChart.value) {
        try {
          barChart.value.resize()
        } catch (error) {
          console.error('柱状图重置大小失败:', error)
        }
      }
      
      if (scatterChart.value) {
        try {
          scatterChart.value.resize()
        } catch (error) {
          console.error('散点图重置大小失败:', error)
        }
      }
    }

    return {
      queryForm,
      loading,
      missionTypes,
      aircraftList,
      matchedAirports,
      analysisData,
      selectedAirport,
      handleMissionTypeChange,
      handleQuery,
      selectAirport
    }
  }
})
</script>

<style scoped>
.takeoff-landing-container {
  width: 100%;
  height: calc(100vh - 64px);
  display: flex;
  background-color: #f5f5f5;
}

.query-panel {
  width: 280px;
  padding: 24px;
  background-color: #fff;
  border-right: 1px solid #e8e8e8;
  overflow-y: auto;
  height: 100%;
  z-index: 10;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.query-panel h3 {
  margin: 0 0 24px 0;
  padding-bottom: 16px;
  font-size: 18px;
  color: #409EFF;
  font-weight: 600;
  border-bottom: 1px solid #e8e8e8;
  line-height: 1;
}

.query-panel h4 {
  margin: 20px 0 16px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.query-results {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.airport-item {
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.3s;
}

.airport-item:hover {
  background-color: #ecf5ff;
}

.airport-item.active {
  background-color: #409EFF;
  color: white;
}

.airport-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.airport-value {
  font-size: 13px;
  color: inherit;
  opacity: 0.8;
}

/* Form styles */
:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  padding: 0 0 8px;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-radio-group) {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio-button__inner) {
  width: 100%;
  text-align: center;
  padding: 0 8px;
  height: 36px;
  line-height: 34px;
  margin-right: 0 !important;
  border-radius: 4px !important;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  height: 36px !important;
  border-radius: 4px !important;
}

:deep(.el-select__tags),
:deep(.el-input__inner) {
  line-height: 34px !important;
}

:deep(.el-button--primary) {
  width: 100%;
  height: 40px;
  font-size: 15px;
  font-weight: 500;
  margin-top: 8px;
  border-radius: 4px;
}

/* 修改任务类型下拉框的样式 */
:deep(.el-select-dropdown) {
  border-radius: 4px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: #ecf5ff;
}

.content-area {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e8e8e8;
}

.scatter-chart-container {
  height: 40%;
  padding: 16px 24px;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.scatter-chart-container h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

#scatterChart {
  width: 100%;
  height: calc(100% - 30px);
}

.map-container {
  flex: 1;
  position: relative;
  background: #fff;
}

#map {
  width: 100%;
  height: 100%;
}

.chart-panel {
  width: 400px;
  padding: 24px;
  background-color: #fff;
  height: 100%;
  overflow-y: auto;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.chart-panel h3 {
  margin: 0 0 24px 0;
  padding-bottom: 16px;
  font-size: 18px;
  color: #409EFF;
  font-weight: 600;
  border-bottom: 1px solid #e8e8e8;
  line-height: 1;
}

#barChart {
  flex: 1;
  width: 100%;
  min-height: 400px;
}

/* Loading spinner */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(64, 158, 255, 0.2);
  border-radius: 50%;
  border-top-color: #409EFF;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Map controls */
:deep(.leaflet-control-container .leaflet-top) {
  top: 10px;
}

:deep(.leaflet-control-container .leaflet-right) {
  right: 10px;
}

/* Airport popup styles */
.airport-popup {
  padding: 12px;
}

.airport-popup h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #409EFF;
  border-bottom: none;
}

.airport-popup p {
  margin: 6px 0;
  font-size: 14px;
  color: #666;
}
</style> 